/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.data;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.data.utils.PMF;
import com.gadglet.params.ProfileFields;

/**
 * Utility class for FriendsInvitation
 *
 */
public class FriendsInvitationUtils {

	static Logger log = Logger.getLogger("FriendsInvitationUtils");
	
	// when the invitation was done on the platfrom level and not via container friends list
	private static final String platformInvitation = "localplatform";
	/**
	 * 
	 * @param user current user profile 
	 * @return a list of the current user existing pending invitations, to stop him from creating duplications
	 * 	 */
	@SuppressWarnings("unchecked")
	public static List <FriendsInvitation> getSenderInvitations(UserProfile user) {
		List <FriendsInvitation> invitations = null;
		
	
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(FriendsInvitation.class);
		
		try {

			query.setFilter("invitedBy == invitedByParam ");
			query.declareParameters("String invitedByParam");
			
			invitations = (List<FriendsInvitation>) query.execute(user.getProfileId());
					

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}

			
		return invitations;
	}
	
	
	/**
	 * Create a new invitation to profile that doesn't exits
	 * <br>See if user exists: 
	 * 			If true, create a relation request<br>
	 * 			If false check for old invitations and create new if needed
	 * @param platformRequestWrapper - current request
	 */
	public static boolean createNewInvitation(UserProfile user, GadgletRequestWrapper platformRequestWrapper){
		
		String  invitedFriend = platformRequestWrapper.getParameter(ProfileFields.PROFILE_FRIEND_ID.getParamName());
		UserProfile newProfileExists = null;
		
			
		if (platformRequestWrapper.getParameter(ProfileFields.PROFILE_FRIEND_ID.getParamName())== null){
			return false;
		}
		
		// check if profile exists
		try {
			newProfileExists = UserProfilesUtils.getPersonProfile(invitedFriend, platformRequestWrapper);
		} catch (Exception e) {
			log.warning(e.getMessage());
		}
		
		if(newProfileExists!=null ){
			
			FriendsInvitation newInvitation = new FriendsInvitation(user.getProfileId(),newProfileExists.getProfileId(), platformInvitation);
			
			saveNewInvitation(newInvitation);
			
			return true;
		}
			
			
		
		// check if invitation exists
		List <FriendsInvitation> pendingInvitations =  getSenderInvitations(user);	
		
		if (pendingInvitations!=null){
			for (FriendsInvitation invitation: pendingInvitations)
				if(invitation.getSendTo().equals(invitedFriend))
					return false;
		}
		
		FriendsInvitation newInvitation = new FriendsInvitation(user.getProfileId(),invitedFriend, platformRequestWrapper.getOpenSocialConsumerKey());
		
		saveNewInvitation(newInvitation);
		
		return true;
	}
	
	/**
	 * @param friendsInvitation
	 * @return
	 */
	public static FriendsInvitation saveNewInvitation(FriendsInvitation friendsInvitation){
		
		FriendsInvitation newFriendsInvitation = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		FriendsInvitation invitatoinExists = null;
		pm.currentTransaction().begin();
		try {
			Query query = pm.newQuery(FriendsInvitation.class);
			query.setFilter("sendTo == sendToParam && container == OpenSocialConsumerKeyParam");
			query.declareParameters("String sendToParam, String OpenSocialConsumerKeyParam");
			query.setUnique(true);
			invitatoinExists = (FriendsInvitation) query.execute(friendsInvitation.getSendTo(),friendsInvitation.getContainer()  );
			
			if(invitatoinExists!=null)
				newFriendsInvitation = invitatoinExists;
			else{
				newFriendsInvitation = pm.makePersistent(friendsInvitation);
				pm.currentTransaction().commit();
			}
			
		} catch (Exception e) {
			log.warning(e.getMessage());
			
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();
			pm.close();
		}
		
		return newFriendsInvitation;
	}
	
	
	
	/**
	 * 
	 * @param platformRequestWrapper
	 * @return
	 */
	public static List <FriendsInvitation> getMyContainerInvitations(GadgletRequestWrapper platformRequestWrapper) {
	
		List <FriendsInvitation> invitations = null;
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(FriendsInvitation.class);
		
		try {

			query.setFilter("sendTo == sendToParam && container == OpenSocialConsumerKeyParam");
			query.declareParameters("String sendToParam, String OpenSocialConsumerKeyParam");
			
			invitations = (List <FriendsInvitation>) query.execute( platformRequestWrapper.getOpenSocialViewerId(),platformRequestWrapper.getOpenSocialConsumerKey() );
					

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}

		
		return invitations;
	}
	
	
	/**
	 * @param request
	 * @return
	 */
	public static List <FriendsInvitation> getMyPlatformInvitations(GadgletRequestWrapper request) {
		
		List <FriendsInvitation> invitations = null;
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(FriendsInvitation.class);
		
		try {

			query.setFilter("sendTo == sendToParam && container == OpenSocialConsumerKeyParam");
			query.declareParameters("String sendToParam, String OpenSocialConsumerKeyParam");
			
			invitations = (List <FriendsInvitation>) query.execute( request.getCurrentUserProfile().getProfileId(),platformInvitation );
					

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}

		
		return invitations;
	}
	
	
	/**
	 * @param request
	 * @return
	 */
	public static boolean isMyInvitationValid(GadgletRequestWrapper request){
FriendsInvitation invitation = null;
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(FriendsInvitation.class);
		boolean sccuess = false;
		
		
		try {
			
			query.setFilter("invitationId == invitationIdParam ");
			query.declareParameters("String invitationIdParam");
			query.setUnique(true);

			invitation = (FriendsInvitation) query.execute( request.getParameter(ProfileFields.PROFILE_INVITATION_ID.getParamName()));
						
			if(invitation != null && (invitation.getSendTo().equals(request.getCurrentUserProfileId()) || invitation.getSendTo().equals(request.getOpenSocialViewerId())))
				sccuess = false;
			
			
			pm.currentTransaction().commit();
			sccuess = true;

		} catch (Exception e) {
			sccuess = false;
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}
			
		return sccuess;
	}
	
	/**
	 * @param request
	 * @return
	 */
	public static boolean deleteInvitation(GadgletRequestWrapper request){
			
	FriendsInvitation invitation = null;
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(FriendsInvitation.class);
		boolean sccuess = false;
		
		
		try {
			
			query.setFilter("invitationId == invitationIdParam ");
			query.declareParameters("String invitationIdParam");
			query.setUnique(true);

			invitation = (FriendsInvitation) query.execute( request.getParameter(ProfileFields.PROFILE_INVITATION_ID.getParamName()));
	
					
			if(invitation != null && (invitation.getSendTo().equals(request.getCurrentUserProfileId()) || invitation.getSendTo().equals(request.getOpenSocialViewerId())))
				pm.deletePersistent(invitation);
			
			
			pm.currentTransaction().commit();
			sccuess = true;

		} catch (Exception e) {
			sccuess = false;
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}
		
		
		
		return sccuess;
	}
	
	
		
}
